package com.kx.center.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kx.center.common.Cache;
import com.kx.center.entity.Account;
import com.kx.center.entity.Company;
import com.kx.center.entity.StoreAppAccount;
import com.kx.center.exception.EmptyTokenException;
import com.kx.center.exception.IllegalTokenException;
import com.kx.center.service.AccountService;
import com.kx.center.service.CompanyService;
import com.kx.center.service.StoreAppAccountService;

/**
 * Created by acmen on 16-1-3.
 */
@Service
public class CommonController {

    @Autowired
    private AccountService accountCommonService;
    @Autowired
    private CompanyService companyCommonService;
	@Autowired
	private StoreAppAccountService storeAppAccountService;


    public Account getCommonUserAccount(HttpServletRequest request){
        String token = request.getHeader("X-Security-Token");
        token = StringUtils.trimToEmpty(token);
        if(token.length() <= 0){
            return null;
        }

        Account account = accountCommonService.findAccountByToken(token);
        return account;
    }

    public Company getCommonUserCompany(int companyId){

        if(companyId <= 0){
            return null;
        }
        Company company = companyCommonService.getCompanyById(companyId);
        return company;
    }

    public Map<String, String> listRequsetParamaters(HttpServletRequest request, String[] paramatersList){
        Map<String,String> result = new HashMap<String,String>();

        for(String key : paramatersList){
            String val = StringUtils.trimToEmpty(request.getParameter(key));
            if(!StringUtils.isEmpty(val)){
                result.put(key,val);
            }
        }

        return result;
    }

    //校验App端传过来的token
    public StoreAppAccount getStoreAppAccount(HttpServletRequest request) throws EmptyTokenException, IllegalTokenException{
    	
        String token = request.getHeader("X-Security-Token");
        token = StringUtils.trimToEmpty(token);
        if(token.length() <= 0){
        	//token为空 抛出异常 进入异常拦截器  返回前端
        	throw new EmptyTokenException();
        }
        //根据token获取账户
        
        StoreAppAccount storeAppAccount = (StoreAppAccount) Cache.get(Cache.APPACCOUNT, token);
        
        if(storeAppAccount == null){
        	throw new IllegalTokenException();
        }
        
        return storeAppAccount;
    }
    
}
